<template>
  <div class="user">
    <el-card class="card">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 搜索框 -->
      <div class="user-search">
        <el-input
        clearable
        placeholder="请输入教师姓名"
        v-model="query"
        class="input-with-select"
        @clear="getUserclear()"
        @input="getUserlist()"
        >
        </el-input>
        <el-button type="success" class="user-btn" @click="addbtn()">添加用户</el-button>
      </div>
      <!-- 表格数据 -->
      <div class="text item" v-loading="loading">
        <el-table
        :data='list'
        stripe
        style="width: 100%"
        height="470"
        >
          <el-table-column
          type="index"
          label=" "
          width="40"
          >
          </el-table-column>
          <el-table-column
          prop="number"
          label="教师编号"
          width="180"
          >
          </el-table-column>
          <el-table-column
          prop="name"
          label="姓名"
          width="120"
          >
          </el-table-column>
          <el-table-column
          prop="roleList"
          label="角色"
          width="180"
          >
          <template  slot-scope="scope">
            <div v-for="item of scope.row.role" :key="item.rid" >
              {{item.name}}
            </div>
          </template>
          </el-table-column>
          <el-table-column
          label="状态"
          width="180"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ccc"
                @change="rolechange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
          prop="editor"
          label="编辑"
          >
            <template slot-scope="scope">
              <el-button
              size="mini"
              plain
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editor(scope.row)"
              >
              </el-button>
              <el-button
              size="mini"
              plain
              type="success"
              icon="el-icon-unlock"
              circle
              @click="editpsw(scope.row)"
              >
              </el-button>
              <el-button
              size="mini"
              plain
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteOpen(scope.row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="Conpager">
        <el-pagination
        class='stu-pager'
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNumber"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalCount"
        >
       </el-pagination>
      </div>
      <!-- 添加组件 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd" style="min-width: 1400px" @opened="ToFocus(1)">
        <el-form :model="form" style="text-align:left;margin-left:10%">
        <el-form-item label="教师编号" :label-width="formLabelWidth">
          <el-input v-model="form.number" autocomplete="off" style="width:370px" ref="one" @keyup.native="jump($event,7)"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" style="width:370px" @keyup.native="jump($event,8)"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-checkbox-group v-model="form.roleIdList">
            <el-checkbox label="1">超管</el-checkbox>
            <el-checkbox label="2">课程建设者</el-checkbox>
            <el-checkbox label="3">课程负责人</el-checkbox>
            <el-checkbox label="4">普通教师</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" type="password" :show-password="true" style="width:370px"></el-input>
        </el-form-item>
        <!-- <el-form-item ="确认密码" :label-width="formLabelWidth">
          <el-input  autocomplete="off" type="password"></el-input>
        </el-form-item> -->
        <el-form-item
        label="状态"
        :label-width="formLabelWidth"
        >
           <template>
              <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ccc"
                active-value="true"
                inactive-value="false"
              >
              </el-switch>
           </template>
        </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
          <el-button type="primary" @click="addform()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑组件 -->
      <el-dialog title="编辑用户" :visible.sync="dialogEditorVisible" style="min-width:1400px" @opened="ToFocus(2)">
        <el-form :model="editform" style="text-align:left;margin-left:10%">
        <el-form-item label="教师编号" :label-width="formLabelWidth">
          <el-input v-model="editform.number" autocomplete="off"  style="width:370px" ref="two" @keyup.native="jump($event,15)"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="editform.name" autocomplete="off"  style="width:370px" @keyup.native="jump($event,16)"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-checkbox-group v-model="editform.role">
            <el-checkbox label="1">超管</el-checkbox>
            <el-checkbox label="2">课程建设者</el-checkbox>
            <el-checkbox label="3">课程负责人</el-checkbox>
            <el-checkbox label="4">普通教师</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
           <template>
              <el-switch
                v-model="editform.status"
                active-color="#13ce66"
                inactive-color="#ccc"
              >
              </el-switch>
            </template>
        </el-form-item>
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="dialogEditorVisible = false">取 消</el-button>
          <el-button type="primary" @click="createdinfo()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改密码组件 -->
      <el-dialog title="修改密码" :visible.sync="dialogpswVisible" style=" min-width: 1300px" @opened="ToFocus(3)">
        <el-form :model="pswform" style="text-align:left;margin-left:10%">
        <el-form-item label="旧密码" :label-width="formLabelWidth">
          <el-input v-model="pswform.password" autocomplete="off" type="password" :show-password="true"  style="width:370px" ref="three" @keyup.native="jump($event,7)">
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-input v-model="pswform.newPassword" autocomplete="off" type="password" :show-password="true" @keyup.native.enter="createdpsw()"  style="width:370px" @keyup.native="jump($event,8)">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="确认密码" :label-width="formLabelWidth">
          <el-input autocomplete="off"></el-input>
        </el-form-item> -->
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="dialogpswVisible = false">取 消</el-button>
          <el-button type="primary" @click="createdpsw()">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    return {
      loading: false,
      value: 'true',
      query: '',
      list: [],
      pageNumber: 1,
      pageSize: 8,
      totalCount: -1,
      role: [],
      tid: '',
      dialogFormVisibleAdd: false,
      dialogEditorVisible: false,
      dialogpswVisible: false,
      formLabelWidth: '120px',
      form: {
        numbder: '',
        name: '',
        roleIdList: [],
        status: true,
        password: ''
      },
      editform: {
        numbder: '',
        name: '',
        role: [],
        status: true,
        password: ''
      },
      pswform: {
        tid: '',
        password: '',
        newPassword: ''
      }
    }
  },
  components: {},
  created () {
    this.getUserlist()
  },
  mounted () {
    this.loading = true
  },
  methods: {
    // 编辑用户信息
    editor (info) {
      this.tid = info.tid
      const formroleIdList = []
      for (var i = 0; i < info.role.length; i++) {
        formroleIdList.push(info.role[i].rid.toString())
      }
      this.editform = {
        number: info.number,
        name: info.name,
        role: formroleIdList,
        status: info.status,
        password: info.password
      }
      this.dialogEditorVisible = true
    },
    async createdinfo () {
      const info = {
        number: this.editform.number,
        name: this.editform.name,
        roleIdList: this.editform.role,
        status: this.editform.status,
        password: this.editform.password,
        tid: this.tid
      }
      // console.log(info)
      const res = await this.$http.put('teacher/update', info)
      // console.log(res)
      if (res.data.status === 200) {
        this.$message.success('修改成功！')
        this.dialogEditorVisible = false
        this.getUserlist()
      } else {
        this.$message.error('error')
      }
    },
    // 修改密码
    editpsw (info) {
      this.tid = info.tid
      this.dialogpswVisible = true
    },
    // 修改密码
    async createdpsw () {
      const pswform = {
        password: this.pswform.password,
        newPassword: this.pswform.newPassword,
        tid: this.tid
      }
      // console.log(pswform)
      const res = await this.$http.post('teacher/repassword', pswform)
      // console.log(res)
      const {status} = res
      if (status === 200) {
        this.$message.success('修改成功！')
        this.dialogpswVisible = false
        this.pswform = {}
        this.getUserlist()
      } else {
        this.$message.error('修改失败！')
      }
    },
    // 添加用户
    addbtn () {
      this.dialogFormVisibleAdd = true
      this.form = {
        roleIdList: []
      }
    },
    async addform () {
      const formroleIdList = []
      const form = this.form
      // console.log('this.form.roleIdList.lenght', form.roleIdList.length)
      for (var i = 0; i < form.roleIdList.length; i++) {
        formroleIdList.push(this.form.roleIdList[i])
      }
      // console.log(formroleIdList)
      this.form = {
        number: this.form.number,
        name: this.form.name,
        roleIdList: formroleIdList,
        status: this.form.status,
        password: this.form.password
      }
      const res = await this.$http.post('teacher/save', this.form)
      // console.log(this.form)
      const {status, msg} = res.data
      // console.log(res)
      if (status === 200) {
        this.$message({
          type: 'success',
          message: '添加成功！'
        })
        this.getUserlist()
        this.dialogFormVisibleAdd = false
      } else {
        this.$message.error(msg)
      }
    },
    // 获取列表数据
    async getUserlist () {
      const AUTH_TOKEN = sessionStorage.getItem('token')
      this.$http.defaults.headers.common['token'] = AUTH_TOKEN
      this.$http.defaults.headers.get['Content-Type'] = 'application/json'
      this.$http.defaults.headers.get['Accept'] = 'application/json'
      const res = await this.$http.get(`teacher/list?pageNum=${this.pageNumber}&pageSize=${this.pageSize}&name=${this.query}`)
      const {code, msg, page} = res.data
      console.log(res)
      if (code !== 200) {
        this.$message.error(msg)
        this.loading = false
      } else {
        this.list = page.list
        this.role = page.list.role
        this.totalCount = page.totalCount
        this.loading = false
      }
    },
    // 修改状态
    async rolechange (info) {
      this.tid = info.tid
      const formroleIdList = []
      for (var i = 0; i < info.role.length; i++) {
        formroleIdList.push(info.role[i].rid.toString())
      }
      const infoform = {
        number: info.number,
        name: info.name,
        roleIdList: formroleIdList,
        status: info.status,
        password: info.password,
        tid: info.tid
      }
      // console.log(infoform)
      const res = await this.$http.put('teacher/update', infoform)
      // console.log(res)
      if (res.data.status === 200) {
        this.$message.success('修改成功！')
      } else {
        this.$message.error(res.data.msg)
      }
      this.getUserlist()
    },
    // 清空搜索回调函数
    getUserclear () {
      this.getUserlist()
    },
    // 删除用户信息
    deleteOpen (info) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const tid = info.tid
        const res = await this.$http.delete('teacher/delete', {data: {ids: [tid]}})
        const {msg, code} = res.data
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserlist()
        } else {
          this.$message.error(msg)
        }
      }).catch(() => {
        this.$message.error('未知错误！')
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // })
      })
    },
    // 分页相关方法
    handleSizeChange (val) {
      this.pageSize = val
      // console.log(`每页 ${val} 条`)
      this.getUserlist()
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      // console.log(`当前页: ${val}`)
      this.getUserlist()
    },
    // 获取焦点
    ToFocus (num) {
      if (num === 1) {
        this.$refs.one.focus()
      }
      if (num === 2) {
        this.$refs.two.focus()
      }
      if (num === 3) {
        this.$refs.three.focus()
      }
    },
    // 按下按键时输入框的焦点转变-目标
    jump (el, index) {
      this.inputs = document.getElementsByTagName('input')
      // console.log(this.inputs)
      if (index === 7 || index === 15) {
        if (el.keyCode === 13 || el.keyCode === 39 || el.keyCode === 40) {
          this.inputs[index + 1].focus()
          this.inputs[index].blur()
        }
      } else if (index === 8 || index === 16) {
        if (el.keyCode === 37 || el.keyCode === 38) {
          // console.log(this.inputs[index - 1])
          this.inputs[index - 1].focus()
          this.inputs[index].blur()
        } else if (el.keyCode === 13) {
        }
      // } else if (index > 7 && index < 15) {
      //   if (el.keyCode === 13 || el.keyCode === 39 || el.keyCode === 40) {
      //     // console.log(this.inputs[index + 1])
      //     this.inputs[index + 1].focus()
      //     this.inputs[index].blur()
      //   } else if (el.keyCode === 37 || el.keyCode === 38) {
      //     // console.log(this.inputs[index - 1])
      //     this.inputs[index - 1].focus()
      //     this.inputs[index].blur()
      //   }
      }
    }
  }
}
</script>

<style scoped lang="stylus">
.user,.card
  height 100%
  min-width: 1200px
  .user-search
    margin-top 15px
    width 100%
    .input-with-select
      width 300px
    .user-btn
      width 100px
  .text
    padding-top 10px
    height 470px
  .Conpager
    margin 0 auto
    padding-top 5px
  .stu-pager
    margin-top 54px
    text-align center
.dialog-footer
  text-align center
</style>
